import jwt
import pymysql
from flask import request
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from app import get_db_connect
from app.models.students import students
from app.models.classes import classes
from app.models.users import users


def check_auth():
    token = request.headers.get('Authorization')
    jwt_data = check_jwt(token)
    if not jwt_data :
        return 404
    else:
        return jwt_data.get('role')


#  验证token,返回payload    pyjwt会自动校验过期时间
def check_jwt(token):
    try:
        jwt_data = jwt.decode(token, key='private_key', algorithms=['HS256'])
        cursor = get_db_connect().cursor(cursor=pymysql.cursors.DictCursor)
        count = cursor.execute("select * from users where uuid = '%s' " % jwt_data['useruuid'])

        user_data = cursor.fetchall()[0]
        schema = userSchema()
        user_data = schema.dump(user_data)
        return user_data
    except Exception as e:
        print(e)
        return False

class userSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = users
        exclude = ['password']

class classSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = classes


class studentSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = students